package com.families.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.families.entity.Album;
import com.families.entity.Result;
import com.families.entity.User;
import com.families.entity.vo.UploadBackVo;
import com.families.entity.vo.UploadVo;
import com.families.service.AlbumService;
import com.families.util.FileUtil;
import com.families.util.ObjectCheck;

@RestController
@RequestMapping("album")
public class AlbumController {
	
	private static final Logger logger = LoggerFactory.getLogger(AlbumController.class);
	
	@Value("${album.path}")
    private String ALBUM_PATH;
	@Autowired
	private AlbumService albumService;
	
	/**
	 * 上传图片
	 * @param photo
	 * @return
	 */
	@RequestMapping(value = "upload1",method = RequestMethod.POST)
	public Result upload1(@RequestParam("photos") MultipartFile[] photos) {
		try {
			if(ObjectCheck.isEmpty(photos)) {
				logger.error("请求参数为空");
				return new Result(Result.ERROR, "请求参数为空", null);
			}
			//判断当前用户
			User user = (User) SecurityUtils.getSubject().getPrincipal();
			if(ObjectCheck.isEmpty(user)) {
				logger.error("用户未登录");
				return new Result(Result.ERROR, "用户未登录", null);
			}
			logger.info("当前用户信息：{}",JSON.toJSONString(user));
			//base转图片
		
			List<String> list=new ArrayList<String>();

			//循环新增
			for (MultipartFile file : photos) {
				try {
					String uploadFile = FileUtil.uploadFile(file, ALBUM_PATH);
					logger.info("文件上传途径：{}",uploadFile);
					File file1=new File(ALBUM_PATH+uploadFile);
					if(!FileUtil.isImage(file1)) {
						logger.error("不是图片文件");
						file1.delete();
						return new Result(Result.ERROR, "不是图片文件", null);
					}
					logger.info("文件上传途径：{}",uploadFile);
					//填充数据
					Album album=new Album();
					album.setFilePath(uploadFile);
					album.setSize(file.getSize());
					album.setState("1");//默认有效
					album.setTitle(file.getName());
					album.setUid(user.getId());
					albumService.insert(album);

				} catch (Exception e) {
					// TODO: handle exception
					String originalFilename = file.getOriginalFilename();
					list.add(originalFilename);
					continue;
				}
			}
			//判断错误列表
			if(!ObjectCheck.isEmpty(list)) {
				if(list.size()==5) {
					logger.info("部分成功：失败：{}",JSON.toJSONString(list));
					return new Result(Result.ERROR, "上传失败", null);	
				}
				logger.info("部分成功：失败：{}",JSON.toJSONString(list));
				return new Result(Result.PART, "部分成功", list);	
			}
			return new Result(Result.SUCCESS, "上传成功", null);			
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("上传异常",e);
			return new Result(Result.ERROR, "上传异常", null);
		}
	}
	
//	@RequestMapping(value = "upload",method = RequestMethod.POST)
//	public Result upload(String photo) {
//		try {
//			if(ObjectCheck.isEmpty(photo)) {
//				logger.error("请求参数为空");
//				return new Result(Result.ERROR, "请求参数为空", null);
//			}
//			//判断当前用户
//			User user = (User) SecurityUtils.getSubject().getPrincipal();
//			if(ObjectCheck.isEmpty(user)) {
//				logger.error("用户未登录");
//				return new Result(Result.ERROR, "用户未登录", null);
//			}
//			logger.info("当前用户信息：{}",JSON.toJSONString(user));
//			//base转图片
//			List<UploadVo> uplist=new ArrayList<UploadVo>();
//			List<String> list=new ArrayList<String>();
//			//判断是否是多图片上传
//			if(photo.contains("-")) {
//			   String[] split = photo.split("-");
//			   for (String string : split) {
//				   UploadVo uploadVo = (UploadVo) JSONObject.parseObject(string, UploadVo.class);
//				   uplist.add(uploadVo);
//			 }
//			}else {
//				 UploadVo uploadVo = (UploadVo) JSONObject.parseObject(photo, UploadVo.class);
//				 uplist.add(uploadVo);
//			}
//			if(ObjectCheck.isEmpty(uplist)) {
//				return new Result(Result.ERROR, "参数有问题", null);	
//			}
//			//循环新增
//			for (UploadVo vo: uplist) {
//				try {
//					Result result = base64ToFile(vo.getBase64(), user);
//					if(result.getCode()==2) {
//						list.add(vo.getName());
//					}
//				} catch (Exception e) {
//					// TODO: handle exception
//					list.add(vo.getName());
//					continue;
//				}
//			}
//			//判断错误列表
//			if(!ObjectCheck.isEmpty(list)) {
//				if(list.size()==5) {
//					logger.info("部分成功：失败：{}",JSON.toJSONString(list));
//					return new Result(Result.ERROR, "上传失败", null);	
//				}
//				logger.info("部分成功：失败：{}",JSON.toJSONString(list));
//				return new Result(Result.PART, "部分成功", list);	
//			}
//			return new Result(Result.SUCCESS, "上传成功", null);			
//		} catch (Exception e) {
//			// TODO: handle exception
//			logger.error("上传异常",e);
//			return new Result(Result.ERROR, "上传异常", null);
//		}
//	}
	///////////////////////////////////////////////////////////////////////////
	
	
	
	/**
	 * 按照用户查询图片
	 * @param photo
	 * @return
	 */
	@RequestMapping("myPictures")
	public Result myPictures() {
		try {
			User user = (User) SecurityUtils.getSubject().getPrincipal();
			if(ObjectCheck.isEmpty(user)) {
				logger.error("用户未登录");
				return new Result(Result.ERROR, "用户未登录", null);
			}
			logger.info("当前用户信息：{}",JSON.toJSONString(user));
			List<UploadBackVo> list = albumService.findByUserId(user.getId());
			if(ObjectCheck.isEmpty(list)) {
				logger.error("未找到图片");
				return new Result(Result.ERROR, "您还没有上传过图片", null);
			}
			return new Result(Result.SUCCESS, "查询成功", list);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("查询异常",e);
			return new Result(Result.ERROR, "查询异常", null);
		}
	}
	/**
	 * 所有用户图片
	 * @param photo
	 * @return
	 */
	@RequestMapping("allPictures")
	public Result allPictures() {
		try {
			List<UploadBackVo> list = albumService.findAll();
			if(ObjectCheck.isEmpty(list)) {
				logger.error("未找到图片");
				return new Result(Result.ERROR, "还没有上传图片", null);
			}
			return new Result(Result.SUCCESS, "查询成功", list);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("查询异常",e);
			return new Result(Result.ERROR, "查询异常", null);
		}
	}
	
	/**
	 * 按照id展示图片
	 * @param photo
	 * @return
	 */
	@RequestMapping("showImage")
	public void showImage(String id,HttpServletResponse response) {
		try {
		//	logger.info("展示图片请求参数：{}",id);
			Album album= albumService.findById(id);
			if(!ObjectCheck.isEmpty(album)) {
			//	logger.info("查询参数{}",JSON.toJSONString(album));
				String path=ALBUM_PATH+album.getFilePath();
		//logger.info("图片路径:{}",path);
				File file=new File(path);
				if(file.exists()) {
					FileUtil.showImage(path, response);
				}else {
					logger.error("图片不存在");
				}
			}else {
				logger.error("未找到对应图片");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("展示异常",e);

		}
	}
	/**
	 * 按照id展示图片
	 * @param photo
	 * @return
	 */
	@RequestMapping("imageDownLoad")
	public void imageDownLoad(String id,HttpServletResponse response,HttpServletRequest request) {
		try {
			logger.info("下载图片请求参数：{}",id);
			Album album= albumService.findById(id);
			if(!ObjectCheck.isEmpty(album)) {
				logger.info("查询参数{}",JSON.toJSONString(album));
				String path=ALBUM_PATH+album.getFilePath();
				logger.info("图片路径:{}",path);
				File file=new File(path);
				if(file.exists()) {
					String replaceAll = UUID.randomUUID().toString().replaceAll("-", "");
					String suffix=album.getFilePath().substring(album.getFilePath().lastIndexOf("."));
					String fileName=replaceAll+suffix;
					FileUtil.downloadFile(response, path, fileName, request);
				}else {
					logger.error("图片不存在");
				}
			}else {
				logger.error("未找到对应图片");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("下载异常",e);
			
		}
	}
//	/**
//	 * 上传私有方法
//	 * @param base64Img
//	 * @param user
//	 * @return
//	 * @throws Exception
//	 */
//	private Result base64ToFile(String base64Img,User user) throws Exception {
//	
//		MultipartFile base64ToMultipart=null;
//		String fileName=null;
//		try {
//		 base64ToMultipart = FileUtil.base64ToMultipart(base64Img);
//		} catch (Exception e) {
//			logger.error("base64位码不正确",e);
//			logger.error("base64位码不正确:{}",base64Img);
//			return new Result(Result.ERROR, "传递图片有问题", null);
//		}
//		if(base64ToMultipart==null) {
//			logger.error("传递参数有误");
//			return new Result(Result.ERROR, "传递图片有问题", null);
//		}
//		
//		String uploadFile = FileUtil.uploadFile(base64ToMultipart, ALBUM_PATH);
//		logger.info("文件上传途径：{}",uploadFile);
//		File file=new File(ALBUM_PATH+uploadFile);
//		if(!FileUtil.isImage(file)) {
//			logger.error("不是图片文件");
//			file.delete();
//			return new Result(Result.ERROR, "不是图片文件", null);
//		}
//		logger.info("文件上传途径：{}",uploadFile);
//		//填充数据
//		Album album=new Album();
//		album.setFilePath(uploadFile);
//		album.setSize(base64ToMultipart.getSize());
//		album.setState("1");//默认有效
//		album.setTitle(base64ToMultipart.getName());
//		album.setUid(user.getId());
//		albumService.insert(album);
//		return new Result(Result.SUCCESS, "上传成功", null);
//	}
	
	
}
